//
//  MyViewController.m
//  JinFuThree
//
//  Created by 爱尚 on 2018/8/29.
//  Copyright © 2018年 毛韶谦. All rights reserved.
//

#import "MyViewController.h"
#import "MyMainView.h"
#import "MyMainCell.h"
#import "MyInfoVC.h"
#import "MyLoansVC.h"
#import "MyMessageVC.h"
#import "MySettingVC.h"
#import "InstamentMyVC.h"
#import "AdvancedApproveVC.h"
#import "MyBankCardVC.h"
#import "MyRequestTools.h"

#define ASUserInfoITTACellIdentify @"ASUserInfoITTACellIdentify"
@interface MyViewController ()<UITableViewDataSource,UITableViewDelegate,MyMainViewDelegate>
@property(nonatomic,strong)UITableView *myTableView;
@property(nonatomic,strong)NSArray<SectionModel *>*sectionArray;
@property(nonatomic,strong)MyMainView *mainView;
@property(nonatomic,strong)UIView *bottomView;
@property(nonatomic,strong)UIView *titleView;

@end

@implementation MyViewController

{
    BOOL isHiddenBar;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initViews];
    // Do any additional setup after loading the view.
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self refreshData];
    [self getUserInfo];
}
//获取用户个人信息
-(void)getUserInfo {
    
    [MyRequestTools getUserInfoDataSuccess:^(id  _Nullable responseObject) {
        
        NSDictionary *dataDic = responseObject[@"data"];
        //authenticationGrade  1 初级 2高级   3审核中
        NSString *authenticationGrade = [NSString stringWithFormat:@"%@",dataDic[@"authenticationGrade"]];
        [self.mainView updateInfoWithGrade:authenticationGrade];
        [AD_UserDefaults setObject:dataDic forKey:@"my_authenticationGrade"];
        if ([authenticationGrade isEqualToString:@"1"]) { //没有高级实名认证
            self.mainView.telLabel.text = dataDic[@"phone"];
            _myTableView.tableFooterView = self.bottomView;
            self.sectionArray = @[];
        }else {
            self.mainView.telLabel.text = dataDic[@"userName"];
            _myTableView.tableFooterView = nil;
            self.sectionArray = [self createDatas];
        }
        [_myTableView reloadData];
    } Failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
        
    }];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    if (isHiddenBar) {
        isHiddenBar = NO;
        [self.navigationController setNavigationBarHidden:NO animated:YES];
    }
    [self refreshData];
}

-(void)initViews {
    
    [self initNavigationBar];
    self.title = @"我的";
    [self preferredStatusBarStyle];
    
    _myTableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _myTableView.backgroundColor = ListMaoBackgroundColor;
    _myTableView.delegate = self;
    _myTableView.dataSource = self;
    _myTableView.showsVerticalScrollIndicator = NO;
    _myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    _mainView = [[MyMainView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidthMao, iPhoneX?440.f/750.f*ScreenWidthMao:352.f/750.f*ScreenWidthMao)];
    _mainView.delegate = self;
    _myTableView.tableHeaderView = _mainView;
    
    [self.view addSubview:_myTableView];
    
    NSDictionary *dataDic = [AD_UserDefaults objectForKey:@"my_authenticationGrade"];
    NSString *authenticationGrade = [NSString stringWithFormat:@"%@",dataDic[@"authenticationGrade"]];
    if ([authenticationGrade isEqualToString:@"1"] && dataDic.allValues) { //高级实名认证
        self.mainView.telLabel.text = dataDic[@"phone"];
        _myTableView.tableFooterView = self.bottomView;
    }else {
        self.mainView.telLabel.text = dataDic[@"userName"];
        _myTableView.tableFooterView = nil;
        self.sectionArray = [self createDatas];
    }
    
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.mas_equalTo(self.view);
    }];
    if (@available(iOS 11.0, *)) {
        self.myTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self.view bringSubviewToFront:self.titleView];
}

- (void)initNavigationBar {
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, ScreenWidthMao, 44)];
    [self.titleView addSubview:titleLabel];
    titleLabel.text = @"我的";
    [titleLabel setTextAlignment:NSTextAlignmentCenter];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font = [UIFont systemFontOfSize:18];
    
    
    UIButton *messageBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.titleView addSubview:messageBtn];
    messageBtn.frame = CGRectMake(ScreenWidthMao - 40 - 8, 2, 40, 40);
    [messageBtn setImage:[[UIImage imageNamed:@"My_nav_ic_message"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [messageBtn addTarget:self action:@selector(messageBtnAction) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *redDot = [[UIImageView alloc] initWithFrame:CGRectMake(40-13, 7, 8, 8)];
    redDot.tag = 12999;
    redDot.image = [UIImage imageNamed:@"home_nav_ic_hongdian"];
    [messageBtn addSubview:redDot];
    
    UIButton *settingBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.titleView addSubview:settingBtn];
    settingBtn.frame = CGRectMake(CGRectGetMinX(messageBtn.frame) - 40 - 5, 2, 40, 40);
    [settingBtn setImage:[[UIImage imageNamed:@"my-nav-ic-set"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [settingBtn addTarget:self action:@selector(settingBtnAction) forControlEvents:UIControlEventTouchUpInside];
}


- (void)refreshData {
    
    UIView *redDat = [self.titleView viewWithTag:12999];
    if ([[Mediator sharedInstance] My_HaveNewMessage]) {
        
        redDat.hidden = NO;
    }else {
        redDat.hidden = YES;
    }
}


//设置字体颜色
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;//白色
}

-(NSArray<SectionModel *>*)createDatas {
    
    CellModel *perfectInformationCell = [CellModel cellModelWithTitle:@"信息完善" subTitle:nil image:@"me_ic_xinxiws" sel:@"goToPerfectInformation"];
    perfectInformationCell.height = 59;
    perfectInformationCell.className = NSStringFromClass([MyMainCell class]);
    perfectInformationCell.reuseIdentifier = ASUserInfoITTACellIdentify;
    perfectInformationCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    CellModel *bankCardBusinessCell = [CellModel cellModelWithTitle:@"银行卡管理" subTitle:nil image:@"me_ic_yinhangka" sel:@"goToBankCardBusiness"];
    bankCardBusinessCell.height = 59;
    bankCardBusinessCell.className = NSStringFromClass([MyMainCell class]);
    bankCardBusinessCell.reuseIdentifier = ASUserInfoITTACellIdentify;
    bankCardBusinessCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    SectionModel *section1 = [SectionModel sectionModelWithTitle:@"" cells:@[perfectInformationCell,bankCardBusinessCell]];
    section1.headerhHeight = 0.01;
    
    
    if ([[Mediator sharedInstance] Login_IsShowFourModule]) {
        
        section1.footerHeight = 10;
        
        CellModel *myLoneCell = [CellModel cellModelWithTitle:@"我的贷款" subTitle:nil image:@"me_ic_wodedaikuan" sel:@"goToMyLone"];
        myLoneCell.height = 59;
        myLoneCell.className = NSStringFromClass([MyMainCell class]);
        myLoneCell.reuseIdentifier = ASUserInfoITTACellIdentify;
        myLoneCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        CellModel *myOverdraftCell = [CellModel cellModelWithTitle:@"我的分期" subTitle:nil image:@"me_ic_wodefenqi" sel:@"goToMyOverdraft"];
        myOverdraftCell.height = 59;
        myOverdraftCell.className = NSStringFromClass([MyMainCell class]);
        myOverdraftCell.reuseIdentifier = ASUserInfoITTACellIdentify;
        myOverdraftCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        SectionModel *section2 = [SectionModel sectionModelWithTitle:@"" cells:@[myLoneCell,myOverdraftCell]];
        section2.headerhHeight = 0.01;
        section2.footerHeight = 0.01;
        
        
        return @[section1,section2];
    }else {
        section1.footerHeight = 0.01;
        return @[section1];
    }
    
    
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    SectionModel * sect = _sectionArray[section];
    return sect.cells.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    SectionModel* sect = _sectionArray[indexPath.section];
    CellModel * item = sect.cells[indexPath.row];
    
    return  item.height;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _sectionArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    SectionModel * sect = _sectionArray[section];
    return sect.headerhHeight;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    SectionModel * sect = _sectionArray[section];
    return sect.footerHeight;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SectionModel* sect = _sectionArray[indexPath.section];
    CellModel * item = sect.cells[indexPath.row];
    
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:item.reuseIdentifier];
    if (!cell) {
        
        cell = [[NSClassFromString(item.className) alloc]initWithStyle:item.style reuseIdentifier:item.reuseIdentifier];
        
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.separatorInset = UIEdgeInsetsMake(0, -10, 0, 0);
    return cell;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    SectionModel * sect = _sectionArray[indexPath.section];
    CellModel * item = sect.cells[indexPath.row];
    
    SEL selector = NSSelectorFromString(@"fillData:");
    if ([cell respondsToSelector:selector]) {
        
        
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Warc-performSelector-leaks"
        [cell performSelector:selector withObject:item];
#pragma clang diagnostic pop
        
    }
    
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SectionModel * sect = _sectionArray[indexPath.section];
    CellModel * item = sect.cells[indexPath.row];
    
    NSString * selString = item.selectorString;
    if (selString) {
        
        SEL selec = NSSelectorFromString(selString);
        if ([self respondsToSelector:selec]) {
            
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Warc-performSelector-leaks"
            
            [self performSelector:selec withObject:nil];
        }
    }
    
}
// 跳转到资料页面
-(void)goToPerfectInformation {
    
    //需先判断是否高级实名认证完成后，才跳转；
    isHiddenBar = YES;
    MyInfoVC *vc = [[MyInfoVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
// 跳转到银行卡页面
-(void)goToBankCardBusiness {
    
    isHiddenBar = YES;
    MyBankCardVC *vc = [[MyBankCardVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

// 跳转到放款页面
-(void)goToMyLone {
    
    isHiddenBar = YES;
    MyLoansVC *vc = [[MyLoansVC alloc] init];
    vc.tap = @"1";
    [self.navigationController pushViewController:vc animated:YES];
}
// 跳转到分期页面
-(void)goToMyOverdraft {
    
    isHiddenBar = YES;
    InstamentMyVC *vc = [[InstamentMyVC alloc] init];
    vc.tap = @"1";
    [self.navigationController pushViewController:vc animated:YES];
}

// 跳转到消息页面
- (void)messageBtnAction {
    
    isHiddenBar = YES;
    MyMessageVC *vc = [[MyMessageVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
//跳转到设置页面
- (void)settingBtnAction {
    
    isHiddenBar = YES;
    MySettingVC *vc = [[MySettingVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
//跳转到高级实名认证页面
- (void)goToGaoJiRenZhengVC {
    
    isHiddenBar = YES;
    AdvancedApproveVC *vc = [[AdvancedApproveVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}


- (UIView *)titleView {
    
    if (!_titleView) {
        _titleView = [[UIView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight-44, ScreenWidthMao, 44)];
        
        
        [self.view addSubview:_titleView];
    }
    return _titleView;
}

- (UIView *)bottomView {
    
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidthMao, ScreenHeight - (iPhoneX?440.f/750.f*ScreenWidthMao:352.f/750.f*ScreenWidthMao) - SafeAreaBottomHeight - 49)];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ic_Mychatu"]];
        [imageView setContentMode:UIViewContentModeScaleAspectFit];
        
        CGFloat width = ScreenWidthMao > 400 ? ScreenWidthMao/2.f : ScreenWidthMao/7.f*4.f;
        
        imageView.frame = CGRectMake(0, 0, width, width);
        imageView.center = _bottomView.center;
        imageView.userInteractionEnabled = YES;
        [_bottomView addSubview:imageView];
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn addTarget:self action:@selector(goToGaoJiRenZhengVC) forControlEvents:UIControlEventTouchUpInside];
        btn.frame = CGRectMake(20, CGRectGetHeight(imageView.frame) - 50, CGRectGetWidth(imageView.frame) - 40, 50);
        [imageView addSubview:btn];
        
    }
    return _bottomView;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
